package com.xxtx.trade.fieldManage.service.impl;

import com.xxtx.trade.agent.dto.ImeiToPhoneDto;
import com.xxtx.trade.common.util.SpringUserContext;
import com.xxtx.trade.common.util.cache.CacheManager;
import com.xxtx.trade.common.util.model.Result;
import com.xxtx.trade.fieldManage.dto.FieldManageDto;
import com.xxtx.trade.fieldManage.mapper.FieldManageMapper;
import com.xxtx.trade.fieldManage.service.FieldManageService;
import com.xxtx.trade.sysUser.dto.PhoneOwnershipDto;
import com.xxtx.trade.sysUser.dto.TradeSysRoleDto;
import com.xxtx.trade.sysUser.mapper.TradeSysUserMapper;
import com.xxtx.trade.sysUser.vo.TradeSysUserVo;
import com.xxtx.trade.thread.HandleAllDataAsync;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.logging.Logger;

@Service
public class FieldManageServiceImpl implements FieldManageService {

    @Autowired
    FieldManageMapper fieldManageMapper;

    @Autowired
    TradeSysUserMapper tradeSysUserMapper;

    @Autowired
    SpringUserContext springUserContext;

    @Autowired
    HandleAllDataAsync handleAllDataAsync;


    @Autowired
    private CacheManager cacheManager;

//    @Value("${default.phoneOwnership}")
//    private String phoneOwnershipCache;

    @Value("${default.phoneOwnership2}")
    private String phoneOwnershipCache2;

    @Override
    public Result getList() {
        Result<Object> result = new Result<>();
        TradeSysUserVo loginUser = springUserContext.getCurrentLoginUser();
        TradeSysRoleDto dto = new TradeSysRoleDto();
        dto.setUserId(loginUser.getId());
        String user_role = tradeSysUserMapper.selectRoleByUserId(dto.getUserId());
        dto.setUser_role(user_role);
        List<FieldManageDto> fieldManageDtoArrayList = fieldManageMapper.getList();
        for (FieldManageDto dto1 : fieldManageDtoArrayList) {
            if (dto1.getSource().equals("1")) dto1.setSource("抖音");
            if (dto1.getSource().equals("3")) dto1.setSource("视频号");
            if (dto1.getSource().equals("5")) dto1.setSource("百度");
            if (dto1.getSource().equals("7")) dto1.setSource("快手");
        }
        // 通过Result的message，给返回携带用户值，用以控制前端的字段显示，超级管理员的角色id是2
        result.setMessage(dto.getUser_role());
        result.setData(fieldManageDtoArrayList);
        return result;
    }

    @Override
    public Result changeStatus(FieldManageDto dto) {
        Result<Object> result = new Result<>();
        // 两种status，0，已禁用；1，已启用，触发service切换状态
        if (dto.getSource().equals("视频号")) dto.setSource("3");
        if (dto.getSource().equals("抖音")) dto.setSource("1");
        if (dto.getSource().equals("百度")) dto.setSource("5");
        if (dto.getSource().equals("快手")) dto.setSource("7");

        if (dto.getStatus().equals("已禁用")) {
            dto.setStatus("0");
            fieldManageMapper.changeStatus(dto);
        } else if (dto.getStatus().equals("已启用")) {
            dto.setStatus("1");
            fieldManageMapper.changeStatus(dto);
        } else {
            result.setCode(400);
            result.setMessage("状态信息错误！");
        }
        return result;
    }

    @Override
    public Result setImeiPhone(ImeiToPhoneDto dto) {
        Result<Object> result = new Result<>();
        try {
            // 进行手机号码的验证，因为要进行excel导入操作，所以
//            /^(?:(?:\+|00)86)?1[3-9]\d{9}$/
            boolean is_valid = dto.getPhone().matches("^(?:(?:\\+|00)86)?1[3-9]\\d{9}$");
            if (!is_valid) {
                // 如果手机号格式不匹配
                result.setCode(400);
                result.setMessage("手机号格式不正确！");
                result.setData(dto);
                return result;
            }

            // 首先查询是否存在该条 imei 记录
            ImeiToPhoneDto if_dto = fieldManageMapper.selectImeiToPhone(dto);
            if (if_dto != null) {
                // 如果记录中已经存在，那么就调用 setImeiPhone，无返回值
                fieldManageMapper.setImeiPhone(dto);
                result.setData(dto);
                return result;
            } else {
                // 如果该条记录中不存在，那么就是新增
                fieldManageMapper.addImeiToPhone(dto);
                result.setData(dto);
                return result;
            }
        } catch (Exception e) {
            result.setCode(400);
            result.setMessage("修改号码错误！");
            return result;
        }
    }

    @Override
    public Result setPhoneOwnership(PhoneOwnershipDto dto) {
        Result result = handleAllDataAsync.asyncPhoneOwnershipInsert(dto);
        return result;
    }

    @Override
    public void phoneOwnershipToRedis() {
        List<PhoneOwnershipDto> phoneOwnershipDtoList = fieldManageMapper.getPhoneOwnershipList();
        for (PhoneOwnershipDto dto : phoneOwnershipDtoList) {
            String info = "" + dto.getOwnershipNum() + "_" + dto.getPlace() + "_" + dto.getTag();
            cacheManager.hAdd(phoneOwnershipCache2, dto.getNumPrefix(), info);

        }
    }
}
